package cn.netdisk.tinynetdisk.controller;

import cn.hutool.core.util.StrUtil;
import cn.netdisk.tinynetdisk.common.entity.ResponseData;
import cn.netdisk.tinynetdisk.service.INetDiskService;

import cn.netdisk.tinynetdisk.service.impl.NetDiskServiceImpl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
public class IndexController {
    @Value("${netDisk.config.baseDir}")
    private String baseDir;
    @Value("#{'${netDisk.config.keys}'.split(',')}")
    private String[] keys;

    @Resource
    private NetDiskServiceImpl netDiskService;


    /**
     * 检查key是否存在
     *
     * @param key 唯一key
     * @return boolean
     * @date 2022/10/10 8:54
     * @author glq
     */
    private boolean checkKeys(String key) {
        for (String s : keys) {
            if (s.equals(key)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param params 接收实体
     * @return cn.netdisk.tinynetdisk.common.entity.ResponseData<java.lang.String>
     * @date 2022/10/10 9:03
     * @author glq
     */
    @PostMapping("login")
    public ResponseData<String> login(@RequestBody Map<String, String> params) {
        String key = params.get("key");
        if (StrUtil.isBlank(key)) {
            return ResponseData.createByErrorMessage("密钥为空");
        }
        if (checkKeys(key)) {
            netDiskService.createDir(baseDir + "/" + key);
            return ResponseData.createBySuccess(key);
        } else {
            return ResponseData.createByErrorMessage("密钥错误");
        }
    }


}
